<?php
/**
 * Created by PhpStorm.
 * User: nmw
 * Date: 18-3-17
 * Time: 上午10:02
 */

/* 创建websocket服务器对象，监听0.0.0.0:9502端口 */
$ws = new swoole_websocket_server("0.0.0.0", 9502);

/* 监听WebSocket连接打开事件 */
$ws->on('open', function ($ws, $request) {
    /* 记录日志，连接时间&链接IP */
    echo "{$request->fd}----time:" . date('Y-m-d H:i:s', $request->server['request_time']);
});

/* 监听WebSocket消息事件 */
$ws->on('message', function ($ws, $frame) {
    /* 记录收到的消息，可以写到日志文件中 */
    echo "Message:{$frame->data}\n";

    /* 遍历所有连接，循环广播 */
    foreach ($ws->connections as $fd)
    {
        $ws->push($frame->fd, $frame->data);
    }
});

/* 监听WebSocket连接关闭事件 */
$ws->on('close', function ($ws, $fd) {
    echo "client-{$fd} is closed\n";
});

$ws->start();
